/**
 * Created by dean on 2017/10/15.
 */
import React, {Component} from "react";
import axios from "axios";
import {
    Panel,
    Glyphicon,
    PageHeader
} from "react-bootstrap";
var Remarkable = require('remarkable');

let articleListUrl = 'http://www.zhangfuwen.com/api/articles?page=0&catid=0';

class ArticleListPanel extends Component {
    constructor(props) {
        super(props);
        this.state = {
            currentSelected: 0,
            articleList: [],
        };
    }
    componentDidMount() {
        axios.get(articleListUrl)
            .then(res => {
                const posts = res.data;
                this.setState({articleList: posts});
            });
    }


    showArticlePage(articleId, index) {
        this.setState({ currentSelected:index })
        this.props.onArticleSelected(articleId)
    }
    render() {
        return (
            <Panel id="sidebar">
                <PageHeader>文章列表
                    <small>Articles</small>
                </PageHeader>
                {
                    this.state.articleList.map(function (elem, i) {
                        return (
                            <li key={i}>
                                <a onClick={this.showArticlePage.bind(this, elem.Id, i)}>
                                    <Glyphicon
                                        glyph="pencil"/> {elem.Title} </a>
                            </li>
                        )
                    }, this)

                }
            </Panel>
        )

    }
}

class ArticlePage extends Component {
    constructor(props) {
        super(props)
        this.state = {
            content: "",
        }
    }

    componentWillReceiveProps(nextProps) {
        if (this.props.articleId !== nextProps.articleId) {
            axios.get("http://www.zhangfuwen.com/article/" +nextProps.articleId + "?content-only=true")
                .then(res => {
                    const posts = res.data;
                    this.setState({content: posts});
                });
        }
    }

    componentDidMount() {
        axios.get("http://www.zhangfuwen.com/article/" + this.props.articleId + "?content-only=true")
            .then(res => {
                const posts = res.data;
                this.setState({content: posts});
            });
    }

    componentDidUpdate(){
        window.scrollTo(0,0)
    }

    render() {

        var md = new Remarkable();
        return (
            <Panel>
                <h1>{this.state.content.Title}</h1>
                <hr/>
                <div dangerouslySetInnerHTML={{__html: md.render(this.state.content.Content)}}></div>
            </Panel>
        )
    }
}

export { ArticleListPanel, ArticlePage }